from django.shortcuts import render
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.utils import PageNum

from drf_haystack.viewsets import HaystackViewSet
from goods.serializers import SKUSSerializers,SKUSearchSeializer
# Create your views here.

from  goods.utils import PageNum
from goods.models import GoodsCategory,SKU

# 获取商品分类信息
class CategoriesView(APIView):

    #面包屑导航分类数据获取
    def get(self,request,pk):
        # 1.获取三级分类id

        # 2 查询三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)
        # 3 通过三级分类查询二级分类
        cat2 = cat3.parent
        # 4 通过二级分类查询一级分类
        cat1 = cat2.parent
        # 5 返回结果
        return Response({
            'cat1':cat1.name,
            'cat2':cat2.name,
            'cat3':cat3.name,
        })

# 获取当前分类的所有商品
class SKUSView(ListAPIView):
    serializer_class = SKUSSerializers
    pagination_class = PageNum # 分页
    filter_backends = [OrderingFilter] # 过滤排序
    ordering_fields = ('create_time','sales','price') # 按照时间 销量 价格排序

    # 重写获取pk类下边所有商品
    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


# 搜索功能
class SKUSearchView(HaystackViewSet):
    index_models = [SKU]
    serializer_class = SKUSearchSeializer
    pagination_class = PageNum # 分页处理







